import { SpecialZoomLevel, Store } from "../../core";

import StoreProps from "./StoreProps";
import useZoom from "./useZoom";
import ZoomPopover from "./ZoomPopover";
import { FC, ReactElement } from "react";

export interface RenderZoomProps {
  scale: number;
  onZoom(newScale: number | SpecialZoomLevel): void;
}

type RenderZoom = (props: RenderZoomProps) => ReactElement;

export interface ZoomProps {
  children?: RenderZoom;
}

const Zoom: FC<{
  children?: RenderZoom;
  store: Store<StoreProps>;
}> = ({ children, store }) => {
  const { scale } = useZoom(store);

  const zoomTo = (newLevel: number | SpecialZoomLevel) => {
    const zoom = store.get("zoom");
    if (zoom) {
      zoom(newLevel);
    }
  };

  const defaultChildren = (props: RenderZoomProps) => (
    <ZoomPopover scale={props.scale} onZoom={props.onZoom} />
  );
  const render = children || defaultChildren;

  return render({
    scale,
    onZoom: zoomTo,
  });
};

export default Zoom;
